﻿using MediatR;
using RearLivestock.Common.Domains.zjy;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.RBAC.Api.Application.zjyApplication.Commands.Permissionses
{
    public class CreatePermissionsHandler : IRequestHandler<CreatePermissionsCommand, Result>
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<CreatePermissionsHandler> _logger;

        /// <summary>
        /// 权限仓储
        /// </summary>
        private readonly IBaseRepository<Permissions> _permissionsRepository;

        /// <summary>
        /// 角色权限仓储
        /// </summary>
        private readonly IBaseRepository<RolePermissions> _rolePermissionsRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger">日志</param>
        /// <param name="permissionsRepository">权限</param>
        /// <param name="rolePermissionsRepository">角色权限</param>
        public CreatePermissionsHandler(ILogger<CreatePermissionsHandler> logger, IBaseRepository<Permissions> permissionsRepository, IBaseRepository<RolePermissions> rolePermissionsRepository)
        {
            _logger = logger;
            _permissionsRepository = permissionsRepository;
            _rolePermissionsRepository = rolePermissionsRepository;
        }

        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(CreatePermissionsCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                var res = await _permissionsRepository.Add(new Permissions()
                {
                    PermissionsId = request.PermissionsId,
                    PermissionsFunction = request.PermissionsFunction,
                    URL = request.URL,
                    ParentLevelId = request.ParentLevelId,
                });
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "权限添加成功";
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("添加权限异常" + ex.Message);
            }
            return result;
        }
    }
}
